import { BaseService, CoolCommException } from "@cool-midway/core";
import { Inject, Provide } from "@midwayjs/core";
import { ProviderProfileService } from "./profile";
import { ProviderProviderService } from "./provider";
import { CarInfoService } from "../../transport/service/car/info";
import { MediaInfoService } from "../../media/service/info";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Equal, In, Repository } from "typeorm";
import { TransportScheduleEntity } from "../../transport/entity/schedule";
import { CapacityEntity } from "../../transport/entity/capacity";
import { Context } from "@midwayjs/koa";
import { ProviderProfileEntity } from "../entity/profile";
import { CarInfoEntity } from "../../transport/entity/car/info";
import { MediaInfoEntity } from "../../media/entity/info";
import type { ProviderMember } from "./provider";

export type ProfileWithTeam = ProviderProfileEntity & { isTeamMaster: boolean; team?: any };
export type MemberWithSchedule = ProviderMember & { schedules: TransportScheduleEntity[] };
export type CarWithSchedule = CarInfoEntity & { schedules: TransportScheduleEntity[] };
export type ProviderOverviewResult = {
  profile: ProfileWithTeam;
  members: MemberWithSchedule[];
  cars: CarWithSchedule[];
  medias: MediaInfoEntity[];
};

@Provide()
export class ProviderOverviewService extends BaseService {
  @Inject()
  profileService: ProviderProfileService;

  @Inject()
  providerService: ProviderProviderService;

  @Inject()
  carInfoService: CarInfoService;

  @Inject()
  mediaInfoService: MediaInfoService;

  @InjectEntityModel(TransportScheduleEntity)
  scheduleModel: Repository<TransportScheduleEntity>;

  @InjectEntityModel(CapacityEntity)
  capacityModel: Repository<CapacityEntity>;

  @Inject()
  ctx: Context;

  /**
   * 聚合：个人信息、团队成员及其排班、团队车辆及排班、团队媒体
   */
  async overview(id): Promise<ProviderOverviewResult> {
    // 个人信息（包含 isTeamMaster 与 team）
    const me = await this.profileService.getProfile(id);

    // 团队成员（合并所属与合作成员）
    const membersRes = await this.providerService.getTeamMembers(me.team?.id);
    const members = Array.isArray(membersRes?.list) ? membersRes.list : [];

    // 计算团队ID
    let teamId: number | null = null;
    if (me?.isTeamMaster && me?.team?.id) {
      teamId = me.team.id;
    } else {
      const myCapacity = await this.capacityModel.findOne({ where: { id: Equal(me.capacityId) } });
      teamId = myCapacity?.teamId ?? null;
    }

    // 团队车辆
    const cars = teamId ? await this.carInfoService.getByTeamId(teamId) : [];

    // 团队媒体
    const medias = teamId ? await this.mediaInfoService.teamListByProviderId({} as any, me.providerId) : [];

    // 成员排班：按成员 capacityId 归组
    const memberCapacityIds = members.map((m: any) => m.capacityId).filter(Boolean);
    const carCapacityIds = cars.map((c: CarInfoEntity) => c.capacityId).filter(Boolean);
    const allCapacityIds = Array.from(new Set<number>([...memberCapacityIds, ...carCapacityIds]));
    const schedules = allCapacityIds.length
      ? await this.scheduleModel.find({ where: { capacityId: In(allCapacityIds) } })
      : [];
    const capacityIdToSchedules: Record<number, TransportScheduleEntity[]> = {};
    for (const s of schedules) {
      if (!capacityIdToSchedules[s.capacityId]) capacityIdToSchedules[s.capacityId] = [];
      capacityIdToSchedules[s.capacityId].push(s);
    }
    const membersWithSchedule = members.map((m: any) => ({
      ...m,
      schedules: m.capacityId ? capacityIdToSchedules[m.capacityId] ?? [] : [],
    })) as MemberWithSchedule[];
    const carsWithSchedule = cars.map((c: CarInfoEntity) => ({
      ...c,
      schedules: c.capacityId ? capacityIdToSchedules[c.capacityId] ?? [] : [],
    })) as CarWithSchedule[];

    return {
      profile: me as ProfileWithTeam,
      members: membersWithSchedule,
      cars: carsWithSchedule,
      medias,
    };
  }
}


